import React, { Suspense, Component } from "react";

class ErrorBoundary extends Component {
  state = {
    hasError: false,
  };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error) {
    // 可以做一些错误的打印
    console.log(error);
  }

  handleRetry = () => {
    this.setState({ hasError: false });
  };

  render() {
    const { hasError } = this.state;
    const { children } = this.props;
    if (hasError) {
      return (
        <div>
          <span>出错了</span>
          <button onClick={this.handleRetry}>请重试</button>
        </div>
      );
    }
    return children;
  }
}

// 路由(组件的)懒加载：
// 1）、React.lazy()和Suspense组件配合
// 2）、边界处理的组件：ErrorBoundary。

const WithLazy = (loadAction) => {
  const MyComponent = React.lazy(loadAction);
  return (props) => (<ErrorBoundary>
    <Suspense fallback={<div>请等待·····</div>}>
      <MyComponent {...props}></MyComponent>
    </Suspense>
  </ErrorBoundary>)
}

export default WithLazy;
